package com.dennytech.tac.widget;

import java.io.ByteArrayOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;

import com.dennytech.tac.net.HttpClientFactory;
import com.dennytech.tac.net.HttpClientFactory.MyHttpClient;
import com.dianping.localcache.CacheManager;
import com.dianping.localcache.FileCacheManager;

public class NetworkThumbView extends NetworkImageView {
	static boolean isCacheInited;

	@SuppressWarnings(value={"unchecked"})
	static CacheManager<byte[]> cache = CacheManager.EMPTY;

	public static void init(Context context) {
		if (isCacheInited)
			return;
		isCacheInited = true;

		cache = new FileCacheManager(context, "fthumb", 4 * 0x100000); // 4m
	}

	public static void clear() {
		cache.clear();
	}

	public NetworkThumbView(Context context) {
		super(context);
	}

	public NetworkThumbView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public NetworkThumbView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected LoadTask createLoadTask() {
		return new CachedLoadTask(this);
	}

	protected static class CachedLoadTask extends LoadTask {
		public CachedLoadTask(NetworkImageView p) {
			super(p);
		}

		@Override
		public Bitmap preDoInBackground(String... params) {
			final String url = params[0];

			//
			// check memcache first
			//
			Bitmap cbitmap = memcache.get(url);
			if (cbitmap != null)
				return cbitmap;

			//
			// check cache
			//
			byte[] bytes = cache.get(url);
			if (bytes != null) {
				Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
				if (bmp != null) {
					NetworkImageView view = parent.get();
					int width = view.getWidth();
					int height = view.getHeight();
					if ((width > 0) && (height > 0)) {
					    bmp = Bitmap.createScaledBitmap(bmp, view.getWidth(), view.getHeight(), view.filterBitmap);
					}
					memcache.put(url, bmp);
					return bmp;
				} else {
					cache.remove(url);
				}
			}

			return null;
		}

		@Override
		public Bitmap doInBackground(String... params) {
			final String url = params[0];
			urlLocks.lock(url);
			MyHttpClient httpClient = null;
			try {
				if (isCancelled())
					return null;

				//
				// download from network
				//
				byte[] bytes = null;
				httpClient = HttpClientFactory.getHttpClient();
				HttpGet get = new HttpGet(url);
				this.get = get;
//				HttpHost proxy = DPEnv.agent().globalProxy();
//				ConnRouteParams.setDefaultProxy(get.getParams(), proxy);
				HttpResponse response = httpClient.execute(get);
				HttpEntity entity = response.getEntity();
				if (this.get == get
						&& response.getStatusLine().getStatusCode() / 100 == 2) {
					ByteArrayOutputStream bos = new ByteArrayOutputStream(
							Math.max(0xFFF, (int) entity.getContentLength()));
					entity.writeTo(bos);
					bytes = bos.toByteArray();
				}
				entity.consumeContent();
				if (this.get != get)
					return null;
				else if (bytes == null)
					return null;
				else {
					Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
						bytes.length);
					if (bitmap != null) {
						cache.put(url, bytes);
						memcache.put(url, bitmap);
					}
					return bitmap;
				}
			} catch (Exception e) {
				return null;
			} catch (Error e) {
				return null;
			} finally {
				this.get = null;
				if (httpClient != null)
					httpClient.recycle();
				urlLocks.unlock(url);
			}
		}
	}
}
